/*
 * @copyright fxsen <br/>
 * @date 2022/4/1 20:16 <br/>
 * @email <a href="mailto:fxsen@foxmail.com">
 * @author fxsen
 */
package com.fxsen.commons.sysmanager.core.service.impl;

import com.fxsen.commons.core.base.common.service.impl.CommonServiceImpl;
import com.fxsen.commons.sysmanager.core.entity.Dictionary;
import com.fxsen.commons.sysmanager.core.entity.DictionaryCategory;
import com.fxsen.commons.sysmanager.core.entity.vo.DictionaryCategoryVo;
import com.fxsen.commons.sysmanager.core.mapper.DictionaryCategoryMapper;
import com.fxsen.commons.sysmanager.core.service.IDictionaryCategoryService;
import com.fxsen.commons.sysmanager.core.service.IDictionaryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 字典类别服务接口实现
 * @author fxsen
 * @date 2022/4/1 20:16
 * @email <a href="mailto:fxsen@foxmail.com">
 */
@Service
public class DictionaryCategoryServiceImpl extends CommonServiceImpl<DictionaryCategoryMapper,DictionaryCategory> implements IDictionaryCategoryService {
    @Autowired
    private DictionaryCategoryMapper dictionaryCategoryMapper;
    @Autowired
    private IDictionaryService dictionaryService;
    @Override
    public List<DictionaryCategoryVo> getDictionaryAll() {
        List<DictionaryCategory> categoryList = this.list();
        List<Dictionary> dictionaryList = dictionaryService.list();
        return generateTree(categoryList,dictionaryList);
    }
    private List<DictionaryCategoryVo> generateTree(List<DictionaryCategory> categorys, List<Dictionary> dictionarys) {
        Map<String, List<Dictionary>> dictionaryMap = new HashMap<String, List<Dictionary>>();
        List<DictionaryCategoryVo> result = new ArrayList<DictionaryCategoryVo>();
        for (int i = 0, len = dictionarys.size(); i < len; i++) {
            Dictionary d = dictionarys.get(i);
            if(dictionaryMap.containsKey(d.getCategoryId())) {
                dictionaryMap.get(d.getCategoryId()).add(d);
            }else {
                List<Dictionary> dictionaryList = new ArrayList<>();
                dictionaryList.add(d);
                dictionaryMap.put(d.getCategoryId(), dictionaryList);
            }
        }
        for (int i = 0, len = categorys.size(); i < len; i++) {
            DictionaryCategory category = categorys.get(i);
            DictionaryCategoryVo dcVO = new DictionaryCategoryVo();
            BeanUtils.copyProperties(category, dcVO);
            dcVO.setChildren(dictionaryMap.get(category.getId()));
            result.add(dcVO);
        }
        return result;
    }
}
